package cn.bookCity.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.w3c.dom.css.ElementCSSInlineStyle;

import com.mchange.v2.beans.BeansUtils;
import com.sun.org.apache.bcel.internal.generic.NEW;

import cn.bookCity.Exception.MyException;
import cn.bookCity.constant.Constant;
import cn.bookCity.convert.MyConvert;
import cn.bookCity.domain.Orders;
import cn.bookCity.domain.User;
import cn.bookCity.service.OrderService;
import cn.bookCity.service.UserService;
import cn.bookCity.util.BeanFactory;
import cn.bookCity.util.MD5Utils;
import cn.bookCity.util.UUIDUtils;

@WebServlet("/book/user")
public class UserServlet extends BaseServlet {
	
	/**
	 * 跳转到 注册页面
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String loginUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		return "/login.jsp";
	}
	
	
	/**
	 * 跳转到 注册页面
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String registUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		return "/register.jsp";
	}
	/**
	 * 用户注册
	 */
	public String regist(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String msg="您已经注册成功，请到邮箱激活！";
		HttpSession session=request.getSession();
		String checkCode=request.getParameter("checkcode");
		String verificationCode =
				 session.getAttribute("verificationCode").toString();
		System.out.println(checkCode+" "+verificationCode);
		if(!checkCode.equals(verificationCode)) {
			msg="验证码错误";
			request.setAttribute("msg", msg);
			return "/register.jsp";
		}
		User user=new User();
		//注册自定义转化器
		 ConvertUtils.register(new MyConvert(), Date.class);
		 BeanUtils.populate(user, request.getParameterMap());
		 //添加用户uid
		//id
		user.setId(UUIDUtils.getId());
		//激活码
		user.setActiveCode(UUIDUtils.getCode());
		//密码加密
		user.setPassword(MD5Utils.md5(user.getPassword()));
		UserService userService=(UserService)BeanFactory.getBean("UserService");
		try {
			userService.regist(user);
		}catch (MyException e) {
			// TODO: handle exception
			msg=e.getMessage();
			return "/errorMessage.jsp";
		}
		request.setAttribute("msg", msg);
		return "/register_success.jsp";
	}
	
	/**
	 * 用户激活
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public String active(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String msg="您的账户已被激活，可以直接登录！";
		String code=request.getParameter("code");
		UserService service=(UserService)BeanFactory.getBean("UserService");
		try {
			service.active(code);
		} catch (MyException e) {
			// TODO: handle exception
		  msg=e.getMessage();
		  return "/errorMessage.jsp";
		}
		request.setAttribute("msg", msg);
		return "/register_success.jsp";
	}
	/**
	 * 用户登录
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	
	public String login(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String  pd=MD5Utils.md5(password);
		String checkcode=request.getParameter("checkcode");
		HttpSession session=request.getSession();
		String verificationCode=session.getAttribute("verificationCode").toString();
		UserService u=(UserService)BeanFactory.getBean("UserService");
		User user=u.login(username, pd);
		if(session.getAttribute("user")!=null) {
			try {
				response.sendRedirect("index.jsp");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;//直接结束方法 流程不在继续
		}
		if(!checkcode.equals(verificationCode)) {
			request.setAttribute("msg", "验证码不正确！");
			return "/login.jsp";
		}
		
		if(user==null) {
			request.setAttribute("msg", "用户名密码不正确");
			return "/login.jsp";
		}
		else {
			if(Constant.USER_IS_ACTIVE!=user.getState()) {
				request.setAttribute("msg", "用户没有被激活");
				return "/login.jsp";
			}
		}
		String autoLogin=request.getParameter("autoLogin");
		if(autoLogin!=null) {
			Cookie cookie=new Cookie("autologin",username+"-"+password);
			cookie.setMaxAge(Integer.parseInt(autoLogin));
            cookie.setPath(request.getContextPath());
			response.addCookie(cookie);
			
		}
		System.out.println();
		request.getSession().setAttribute("user", user);;
//		response.sendRedirect(request.getContextPath()+"/");
		String preUrl=request.getHeader("Referer");
		if(preUrl==null||preUrl.equals("")) {
			return "/index.jsp";
		}else if(preUrl.contains("login.jsp")) {
			return "/index.jsp";
		}else {
			return "/index.jsp";
		}
		
	}
     /**
      * 用户登出
      * @param request
      * @param response
      * @return
      * @throws Exception
      */
	public String logout(HttpServletRequest request,HttpServletResponse response) throws Exception{
		HttpSession session=request.getSession();
		session.invalidate();
		response.sendRedirect(request.getContextPath());
		return null;
	}
	/**
	 * 检验用户是否被注册
	 */
	public String checkUser(HttpServletRequest request,HttpServletResponse response) throws Exception{
		PrintWriter out=response.getWriter();
		String username=request.getParameter("username");
		UserService u=(UserService)BeanFactory.getBean("UserService");
		User user=u.checkUser(username);
		if(user==null) {
			out.print(true);
		}else {
			out.print(false);
		}
		return null;
	}
	/**
	 * 检验邮箱是否被注册
	 */
	public String checkEmail(HttpServletRequest request,HttpServletResponse response)throws Exception{
		PrintWriter out=response.getWriter();
		String email=request.getParameter("email");
		UserService u=(UserService)BeanFactory.getBean("UserService");
		User user=u.checkEmail(email);
        if(user==null) {
        	out.print(true);
        }else {
        	out.print(false);
        }
        return null;
	}
	
	public String showAllUser(HttpServletRequest request,HttpServletResponse response) {
		UserService u=(UserService)BeanFactory.getBean("UserService");
		List<User> usrs = u.get();
		
		request.setAttribute("usrs", usrs);
		
		return "/manager/user/orderList.jsp";
	}
	
	
	public String deleteUser(HttpServletRequest request,HttpServletResponse response) {
		UserService u=(UserService)BeanFactory.getBean("UserService");
		String uid=request.getParameter("uid");
		u.del(uid);
		
		List<User> usrs = u.get();
		
		request.setAttribute("usrs", usrs);
		
		return "/manager/user/orderList.jsp";

	}
}
